package com.hzit.order.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzit.common.utils.IdWorker;
import com.hzit.common.utils.TbPayLog;
import com.hzit.order.dao.OrderDao;
import com.hzit.order.dao.OrderItemDao;
import com.hzit.order.dao.PayLogDao;
import com.hzit.order.entity.Cart;
import com.hzit.order.entity.TbAddress;
import com.hzit.order.entity.TbOrder;
import com.hzit.order.entity.TbOrderItem;
import com.hzit.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.swing.StringUIClientPropertyKey;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderDao, TbOrder> implements OrderService {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private IdWorker idWorker;
	@Autowired
	private OrderItemDao itemDao;
	@Autowired
	private PayLogDao payLogDao;

	//1. 根据登录名查询购物车列表
	@Override
	public List<Cart> findCartList(String name) {
		//1.1 得到购物车列表
		String cartList = (String) redisTemplate.opsForHash().get("cartList", name);
		//1.2 判断是否有值
		if(StrUtil.isNotBlank(cartList)){
			return JSON.parseArray(cartList,Cart.class);
		}
		return new ArrayList<>();
	}

	//2. 添加到订单及订单项
	@Override
	@Transactional
	public void add(String name,TbOrder tbOrder) {
		//2.1 得到当前登录用户的购物车列表
		List<Cart> cartList = findCartList(name);
		//2.2 遍历购物车列表
		//2.2.1 定义订单总金额
		double total = 0;
		// 定义订单id编号列表
		List<String> ids = new ArrayList<>();
		for (Cart cart : cartList) {
			double sum = 0;
			//2.3 定义要添加的订单对象
			TbOrder order = new TbOrder();
			long id = idWorker.nextId();
			ids.add(id + "");
			order.setOrderId(id);
			order.setCreateTime(new Date());
			order.setPaymentType(tbOrder.getPaymentType()); // 支付类型
			order.setStatus("1");                           // 未付款
			order.setReceiver(tbOrder.getReceiver());       // 联系人
			order.setReceiverAreaName(tbOrder.getReceiverAreaName()); // 住址
			order.setReceiverMobile(tbOrder.getReceiverMobile());     // 手机号
			order.setSellerId(cart.getSellerId());
			order.setUpdateTime(new Date());
			order.setUserId(name);

			//2.4 处理订单项
			for (TbOrderItem orderItem : cart.getOrderItemList()) {
				long orderItemId = idWorker.nextId();
				orderItem.setId(orderItemId);
				orderItem.setOrderId(id);
				//累加小计
				sum += orderItem.getTotalFee().doubleValue();
				//开始添加
				itemDao.insert(orderItem);
			}
			total += sum;
			//为订单设置总金额
			order.setPayment(new BigDecimal(sum));
			// 添加订单
			this.save(order);
		}

		//todo... 添加数据到支付日志中
		if(tbOrder.getPaymentType().equals("1")){
			//1. 构造支付日志数据
			TbPayLog payLog = new TbPayLog();
			payLog.setCreateTime(new Date());                 // 创建时间
			payLog.setOutTradeNo(idWorker.nextId() + "");     // 订单编号
			payLog.setPayType(tbOrder.getPaymentType());      // 支付类型
			payLog.setTotalFee((long)(total * 100));          // 订单总金额
			payLog.setTradeState("0");                        // 订单状态 0: 未付款 1： 己付款
			payLog.setUserId(name);                           // 用户
			payLog.setOrderList(ids.toString().replace("[","").replace("]",""));
			//取出订单关联的第一个订单项的标题作为支付的标题
			Cart cart = cartList.get(0);
			TbOrderItem tbOrderItem = cart.getOrderItemList().get(0);
			String title = tbOrderItem.getTitle();
			payLog.setSubject(title);
			//2. 添加到数据库中
			payLogDao.insert(payLog);

			//3. 将支付日志放到redis中
			redisTemplate.opsForValue().set(name + "_payLog",JSON.toJSONString(payLog));
		}
	}

	//3. 保存订单 (分支事务)
	@Override
	@Transactional
	public void saveOrder() {
		TbOrder order = new TbOrder();
		order.setUserId("zhangsan");
		order.setStatus("1");
		this.save(order);
		int i = 10 / 0;
	}

	//3.  从redis中得到支付日志
	@Override
	public TbPayLog getPayLogByName(String name) {
		String s = redisTemplate.opsForValue().get(name + "_payLog");
		TbPayLog payLog = JSON.parseObject(s, TbPayLog.class);
		return payLog;
	}

	//4. 根据用户名查询订单及订单项列表
	@Override
	public List<TbOrder> findOrderListByName(String name) {
		//4.1 根据登录名查询订单列表
		List<TbOrder> orderList = this.list(new QueryWrapper<TbOrder>().eq("user_id", name).orderByDesc("create_time"));
		//4.2 查询出各个订单关联的订单项集合
		for (TbOrder order : orderList) {
			//4.2.1 根据订单编号查询出订单关联的订单项集合
			List<TbOrderItem> orderItems = itemDao.selectList(new QueryWrapper<TbOrderItem>().eq("order_id", order.getOrderId()));
			//4.2.2 将订单项集合与订单进行绑定
			order.setOrderItems(orderItems);
		}
		return orderList;
	}
}
